package com.app.config.Druid;


/**
 * druid 配置多数据源
 */
import com.alibaba.druid.pool.DruidDataSource;
import com.app.common.utils.DataSourceComposeUtils;
import com.app.config.datasource.DynamicDataSource;
import com.app.config.datasource.DynamicDataSourceUtil;
import com.app.modules.code.domain.Sysdbconfig;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.sqlite.SQLiteDataSource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class DruidConfig {


    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Bean()
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource() {
        SQLiteDataSource dataSource = new SQLiteDataSource();
        dataSource.setUrl(dataSourceProperties.getUrl());
        return dataSource;
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("master", masterDataSource);
        // 从数据库中直接读取数据库
        JdbcTemplate jdbcTemplate = new JdbcTemplate(masterDataSource);

        RowMapper<Sysdbconfig> rowMapper = new BeanPropertyRowMapper<Sysdbconfig>(Sysdbconfig.class);
        List<Sysdbconfig> dblist = jdbcTemplate.query("select * from tb_sysdbconfig",rowMapper);


       // List<Sysdatasource> dblist = jdbcTemplate.query("select * from tb_sysdatasource",new Object[] {}, new BeanPropertyRowMapper<Sysdatasource>(Sysdatasource.class));
        if(dblist != null && dblist.size() > 0) {
            for(Sysdbconfig db_item : dblist) {
                DruidDataSource dds = DataSourceComposeUtils.composeDruidDataSource(db_item);
                targetDataSources.put(db_item.getDbname()+"-"+ db_item.getId(), dds);
            }
        }
        DynamicDataSourceUtil.setTargetDataSources(targetDataSources);
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }

    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(masterDataSource());
        return sqlSessionFactoryBean.getObject();
    }







}
